package com.ruoyi.develop.lvYifahuo.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;

import javax.annotation.Resource;

import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.finance.financeAr.domain.FinanceAr;
import com.ruoyi.develop.finance.financeAr.service.IFinanceArService;
import com.ruoyi.develop.goodsOrderIn.domain.GoodsOrderIn;
import com.ruoyi.develop.goodsOrderIn.mapper.GoodsOrderInMapper;
import com.ruoyi.develop.goodsSale.domain.GoodsSale;
import com.ruoyi.develop.goodsSale.service.IGoodsSaleService;
import com.ruoyi.develop.goodsSaleMaterialDetail.domain.GoodsSaleMaterialDetail;
import com.ruoyi.develop.goodsSaleMaterialDetail.service.IGoodsSaleMaterialDetailService;
import com.ruoyi.develop.lvFahuotongzhi.service.ILvFahuotongzhiService;
import com.ruoyi.develop.lvRukumingxi.domain.LvRukumingxi;
import com.ruoyi.develop.lvRukumingxi.mapper.LvRukumingxiMapper;
import com.ruoyi.develop.lvRukumingxi.service.impl.LvRukumingxiServiceImpl;
import com.ruoyi.develop.lvYifahuomingxi.domain.LvYifahuomingxi;
import com.ruoyi.develop.lvYifahuomingxi.mapper.LvYifahuomingxiMapper;
import com.ruoyi.develop.projectBaseInfo.domain.ProjectBaseInfo;
import com.ruoyi.develop.projectBaseInfo.mapper.ProjectBaseInfoMapper;
import com.ruoyi.develop.projectBaseInfo.service.IProjectBaseInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.develop.lvYifahuo.mapper.LvYifahuoMapper;
import com.ruoyi.develop.lvYifahuo.domain.LvYifahuo;
import com.ruoyi.develop.lvYifahuo.service.ILvYifahuoService;

/**
 * 发货单Service业务层处理
 *
 * @author qh
 * @date 2024-10-08
 */
@Service
public class LvYifahuoServiceImpl implements ILvYifahuoService {
    @Resource
    private LvYifahuoMapper lvYifahuoMapper;
    @Resource
    private LvYifahuomingxiMapper lvYifahuomingxiMapper;
    @Resource
    private GoodsOrderInMapper goodsOrderInMapper;
    @Resource
    private LvRukumingxiServiceImpl lvRukumingxiService;
    @Autowired
    private ILvFahuotongzhiService iLvFahuotongzhiService;
    @Autowired
    private IGoodsSaleService goodsSaleService;
    @Autowired
    private IProjectBaseInfoService projectBaseInfoService;
    @Autowired
    private IFinanceArService financeArService;

    @Autowired
    private IGoodsSaleMaterialDetailService iGoodsSaleMaterialDetail;
    @Resource
    private LvRukumingxiMapper lvRukumingxiMapper;


    /**
     * 查询发货单
     *
     * @param id 发货单主键
     * @return 发货单
     */
    @Override
    public LvYifahuo selectById(String id) {
        return lvYifahuoMapper.selectById(id);
    }

    /**
     * 查询发货单列表
     *
     * @param entity 发货单
     * @return 发货单
     */
    @Override
    public List<LvYifahuo> selectList(LvYifahuo entity) {
        return lvYifahuoMapper.selectList(entity);
    }

    /**
     * 新增发货单
     *
     * @param entity 发货单
     * @return 结果
     */
    @Override
    public int insert(LvYifahuo entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());

        if(StringUtils.isBlank(entity.getNos())){
            String todayDate = DateUtils.dateTime();
            String codeMax = lvYifahuoMapper.getMaxNosByDate(todayDate);
            // 如果存在 则加1 否则返回0001
            if (codeMax != null) {
                codeMax =  Long.parseLong(codeMax) + 1+"";
            }
            else {
                codeMax = todayDate+"0001";
            }
            entity.setNos(codeMax);
        }

        return lvYifahuoMapper.insert(entity);
    }

    /**
     * 修改发货单
     *
     * @param entity 发货单
     * @return 结果
     */
    @Override
    public int update(LvYifahuo entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        return lvYifahuoMapper.update(entity);
    }

    /**
     * 批量删除发货单
     *
     * @param ids 需要删除的发货单主键
     * @return 结果
     */
    @Override
    public int deleteByIds(String[] ids) {
        // 删除 已发货明细
        for(String id : ids) {
            LvYifahuomingxi lvYifahuomingxi = new LvYifahuomingxi();
            lvYifahuomingxi.setFahuoId(id);
            List<LvYifahuomingxi> lvYifahuomingxiList = lvYifahuomingxiMapper.selectList(lvYifahuomingxi);
            for (LvYifahuomingxi detail : lvYifahuomingxiList) {
                lvYifahuomingxiMapper.deleteById(detail.getId());
                // 返回GoodsSale的库存
                GoodsSale goodsSale = goodsSaleService.selectById(detail.getSaleId());
                goodsSale.setFahuoShengyu(goodsSale.getFahuoShengyu().add(detail.getShuliang()));
                goodsSale.setFahuoCount(goodsSale.getFahuoCount().subtract(detail.getShuliang()));
                goodsSaleService.update(goodsSale);
            }
        }
        return lvYifahuoMapper.deleteByIds(ids);
    }

    //到货回执
    public int updateDaohuohuizhi(LvYifahuo entity) {
        lvYifahuomingxiMapper.updateStatusByFahuoId(entity.getId(), BusinessConstants.YIFAHUO_4);
        update(entity);
        List<LvYifahuomingxi> lvYifahuomingxList=lvYifahuomingxiMapper.selectByFahuoId(entity.getId());
        String projectIds="";
        for(LvYifahuomingxi lvYifahuomingxi:lvYifahuomingxList){
            GoodsSale goodsSale=goodsSaleService.selectById(lvYifahuomingxi.getSaleId());
            if(goodsSale.getFahuoShengyu().compareTo(BigDecimal.ZERO) >0 ){
                //System.out.println("goodsSale.getFahuoShengyu():::::::::"+goodsSale.getFahuoShengyu());
            }else{
               goodsSale.setStatus(BusinessConstants.SALE_TYPE_7);//已收货
               goodsSaleService.update(goodsSale);
            }
            if(projectIds.contains(goodsSale.getProjectId())){
                //System.out.println("projectId::::::::“”“”“:"+goodsSale.getProjectId());
            }else{
                projectIds=goodsSale.getProjectId()+","+projectIds;
            }
        }
        String[] projectIdList=projectIds.split(",");
        for(String projectId:projectIdList){
            if(StringUtils.isNotBlank(projectId)) {
                List<GoodsSale> goodsSaleList = goodsSaleService.selectListYifahuo(projectId, BusinessConstants.SALE_TYPE_7);
                if (goodsSaleList.size() == 0) {
                    ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(projectId);
                    projectBaseInfo.setStatus(BusinessConstants.SALE_TYPE_7);
                    projectBaseInfoService.update(projectBaseInfo);
                }
            }
        }
        return lvYifahuoMapper.shenhetongguo(entity.getId(), BusinessConstants.YIFAHUO_4);
    }

    //已发货审核通过
    @Override
    public int shenhetongguo(String id) {
        LvYifahuo lvYifahuo = lvYifahuoMapper.selectById(id);
        iLvFahuotongzhiService.updateState(lvYifahuo.getTongzhiId(), BusinessConstants.FAHUOTONGZHI_2);
        //更改发货明细状态
        lvYifahuomingxiMapper.updateStatusByFahuoId(id, BusinessConstants.YIFAHUO_2);
        List<LvYifahuomingxi> lvYifahuomingxiList = lvYifahuomingxiMapper.selectByFahuoId(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = sdf.format(new Date());
        for (LvYifahuomingxi lvYifahuomingxi : lvYifahuomingxiList) {
            //减库存
            GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(lvYifahuomingxi.getGoodsId());
            //新增出库单产品明细
            LvRukumingxi lvRukumingxi = new LvRukumingxi();
            ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(lvYifahuomingxi.getProId());
            GoodsSale goodsSale = goodsSaleService.selectById(lvYifahuomingxi.getSaleId());
            if (projectBaseInfo != null) {
                if (StringUtils.isNotBlank(projectBaseInfo.getCustomId())) {
                    lvRukumingxi.setCustomerId(projectBaseInfo.getCustomId());
                }
                if (StringUtils.isNotBlank(projectBaseInfo.getCustomName())) {
                    lvRukumingxi.setCustomerName(projectBaseInfo.getCustomName());
                }
                lvRukumingxi.setNos(time);
                lvRukumingxi.setSaleId(projectBaseInfo.getSaleId());
                lvRukumingxi.setSaleName(projectBaseInfo.getSalesmanName());
                lvRukumingxi.setGoodsTotalPrice(projectBaseInfo.getSaleMoney());
                lvRukumingxi.setProjectId(projectBaseInfo.getId());
                lvRukumingxi.setProjectName(projectBaseInfo.getName());
                lvRukumingxi.setProjectNo(projectBaseInfo.getCode());
                lvRukumingxi.setGoodsId(goodsOrderIn.getId());
                lvRukumingxi.setCode(goodsOrderIn.getCode());
                lvRukumingxi.setGoodsType(BusinessConstants.GOODS_TYPE_MATERIAL);//产品类型
                lvRukumingxi.setType(BusinessConstants.TYPR_CHUKU);//产品出入库类型
                lvRukumingxi.setStatus(BusinessConstants.STORAGE_STATE_YES);
                //lvRukumingxi.setGoodsBuyPrice(lvYifahuomingxi.getDanjian());//发货成本单件
                //lvRukumingxi.setGoodsBuyTotal(lvYifahuomingxi.getMoney());//发货成本总价
                //lvRukumingxi.setGoodsProfit(goodsSale.getGoodsTotalPrice().subtract(lvYifahuomingxi.getMoney()));//利润=销售价-成本
                lvRukumingxi.setDaohuoCount(lvYifahuomingxi.getShuliang());//出入库数量
                if (BusinessConstants.GOODS_TYPE_MATERIAL.equals(lvYifahuomingxi.getGoodsType())) {
                    lvRukumingxi.setDun(goodsSale.getCount());//到货吨位
                }
                lvRukumingxi.setUnit(lvYifahuomingxi.getDanwei());
                lvRukumingxi.setRukudate(new Date());
                lvRukumingxi.setRukuno(lvYifahuomingxi.getFahuoNo());
                lvRukumingxi.setRemark("发货审核通过："+lvYifahuomingxi.getRemark());
                lvRukumingxi.setGoodsSaleId(goodsSale.getId());

                GoodsSaleMaterialDetail goodsSaleMaterialDetail=new GoodsSaleMaterialDetail();
                goodsSaleMaterialDetail.setYifahuomingxiId(lvYifahuomingxi.getId());
                List<GoodsSaleMaterialDetail> goodsSaleMaterialDetailList=iGoodsSaleMaterialDetail.selectList(goodsSaleMaterialDetail);
                if(goodsSaleMaterialDetailList.size()>0){
                    for(GoodsSaleMaterialDetail goodsSaleMaterialDetail1:goodsSaleMaterialDetailList){
                        LvRukumingxi lvRukumingxi1=lvRukumingxiService.selectById(goodsSaleMaterialDetail1.getRukuId());
                        if(lvRukumingxi1!=null){
                            if(lvRukumingxi1.getGoodsBuyTotal()!=null){
                                LvRukumingxi lvRukumingxiBeginMoney=lvRukumingxiMapper.selectBeginMoney();
                                lvRukumingxi.setBeginMoney(lvRukumingxiBeginMoney.getBeginMoney().subtract(goodsSaleMaterialDetail1.getGoodsBuyTotal()));
                            }
                        }
                    }
                }
                lvRukumingxiService.insert(lvRukumingxi);

                //更新销售订单的产品
//                goodsSale.setFahuoCount(goodsSale.getFahuoCount().add(lvYifahuomingxi.getShuliang()));
//                goodsSale.setFahuoShengyu(goodsSale.getFahuoShengyu().subtract(lvYifahuomingxi.getShuliang()));
                 /*if(goodsSale.getFahuoShengyu().compareTo(BigDecimal.ZERO)){
                    goodsSale.setStatus(BusinessConstants.SALE_TYPE_7);//全部发货
                }else{*/
                    goodsSale.setStatus(BusinessConstants.SALE_TYPE_6);//发货中
                /*}*/
                //goodsSale.setGoodsBuyPrice(lvYifahuomingxi.getDanjian());//发货成本单件
                //goodsSale.setGoodsBuyTotal(lvYifahuomingxi.getMoney());//发货成本总价
                //goodsSale.setGoodsProfit(projectBaseInfo.getSaleMoney().subtract(lvYifahuomingxi.getMoney()));//利润=销售价-成本
                goodsSaleService.update(goodsSale);

                //更新销售订单的利润
                projectBaseInfo.setStatus(BusinessConstants.SALE_TYPE_6);
                //projectBaseInfo.setGoodsBuyPrice(lvYifahuomingxi.getDanjian());//发货成本单件
                //projectBaseInfo.setGoodsBuyTotal(lvYifahuomingxi.getMoney());//发货成本总价
                //projectBaseInfo.setGoodsProfit(projectBaseInfo.getSaleMoney().subtract(lvYifahuomingxi.getMoney()));//利润=销售价-成本
                projectBaseInfoService.update(projectBaseInfo);

                //更新库存数量 和剩余库存数量
                // 1.发多少货 库存就减去多少  2.可用数量 减少量 = 发货总数量-锁定数量
                goodsOrderIn.setCount(goodsOrderIn.getCount().subtract(lvYifahuomingxi.getShuliang()));//库存数量=库存数量-发货数量

                BigDecimal lockCount = goodsSale.getLockCount();
                // 该订单产品 发货总数量
                BigDecimal goodsSendTotal = lvYifahuomingxiMapper.goodsSendTotalCount(goodsSale.getId());
                if(goodsSendTotal.subtract(lockCount).compareTo(BigDecimal.ZERO) > 0){
                    goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(goodsSendTotal.subtract(lockCount)));
                }
                goodsOrderInMapper.update(goodsOrderIn);

            } else {
                return 0;
            }

        }
        //更改发货货单
        return lvYifahuoMapper.shenhetongguo(id, BusinessConstants.YIFAHUO_2);
    }

    @Override
    public int tishenCaiwu(String id) {
        return lvYifahuoMapper.shenhetongguo(id, BusinessConstants.YIFAHUO_1);
    }
    /**
     * 删除发货单信息
     *
     * @param id 发货单主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return lvYifahuoMapper.deleteById(id);
    }

    @Override
    public int financeConfirm(String id) {
        LvYifahuo lvYifahuo = lvYifahuoMapper.selectById(id);
        lvYifahuo.setStatus(BusinessConstants.YIFAHUO_6);
        lvYifahuoMapper.update(lvYifahuo);
        financeArService.addBySend(lvYifahuo);
        return 1;
    }


}
